
/**
 *
 */
const fs = require("fs")
const chalk = require('chalk');
const tts_save = require('./tts/tts-transformation');
const platform = require('os').platform();

// mac / linux
const player = require('play-sound')(opts = {})
//windows
const sound = require('sound-play')

function read(fileName, text = '') {
  let path = getPageh(fileName);
  exists(path, (exists) => {
    if (exists) {
      reading(path);
    }
    else {
      save(fileName, text, (res) => {
        if (res) reading(path)
      });
    }
  })
}

function save(fileName, text = '', callback = (res) => { }) {
  tts_save.save(fileName, text, callback)
}


//检测目录是否存在，不存在创建一个
function exists(filePath, callback = (exists) => { }) {
  fs.stat(filePath, (error, stats) => {
    let exists = false
    if (!error) {
      if (stats && stats.isFile()) {
        exists = true
      }
    }
    const fsRes = exists ? '文件存在' : '文件不存在'
    const res = '检测结果：' + filePath + '\n目录文件=>' + fsRes;
    console.log('')
    console.log(chalk.red.bold.bgWhite(res));
    console.log('')
    callback && callback(exists);
  })
}

function getPageh(fileName) {
  return __dirname + '/assets/' + fileName;
}

function reading(path, count = 0) {
  count++;
  if (count === 1) {
    repeatPlay(path, count)
  }
  else {
    setTimeout(() => {
      repeatPlay(path, count)
    }, 2000);
  }
}

function repeatPlay(path, count) {
  if (count < 5) {
    playOnce(path, count)
  }
  console.log('reading i=', count++);
}

function playOnce(path, count) {
  findPlatform(() => {
    //win
    try {
      sound.play(path)
        .then(() => {
          reading(path, count);
        });
    } catch (error) {
      throw err;
    }
  },
    () => {
      //mac / linux
      player.play(path, { afplay: ['-v', 10] /* lower volume for afplay on OSX */ }, function (err) {
        console.log("Audio finished");
        if (err) {
          throw err;
        }
        else {
          reading(path, count);
        }
      });
    })
}

function findPlatform(winCall = () => { }, otherCall = () => { }) {
  if (/^win/.test(platform)) return winCall && winCall();
  otherCall && otherCall();
}


module.exports = { read, save };